package com.fuhao.api.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fuhao.api.config.AlipayConfig;
import com.fuhao.api.dao.PaymentInfoDao;
import com.fuhao.api.entity.PaymentInfo;
import com.fuhao.api.service.PayService;
import com.fuhao.base.BaseApiService;
import com.fuhao.base.BaseRedisService;
import com.fuhao.base.ResponseBase;
import com.fuhao.constants.Constants;
import com.fuhao.utils.TokenUtils;

@RestController
public class PayServiceImpl implements PayService{
	@Autowired
	private PaymentInfoDao payDao;
	@Autowired
	private BaseRedisService redisService;
	@Autowired
	private AlipayConfig alipayConfig;
	@Override
	public ResponseBase createToken(@RequestBody PaymentInfo paymentInfo) {
		//创建支付请求信息
		Integer id = payDao.savePaymentType(paymentInfo);
		if(id <= 0 ) {
			return BaseApiService.setResultError("创建支付订单失败");
		}
		//生成对应的token
		String payToken = TokenUtils.getPayToken();
		//存放token到redis中，key:token,value:支付id
		redisService.setString(payToken, paymentInfo.getId()+"", Constants.TOKEN_PAY_TIME);
		//返回token
		JSONObject data = new JSONObject();
		data.put("payToken", payToken);
		return BaseApiService.setResultSuccess(data);
	}
	@Override
	public ResponseBase findPayToken(@RequestParam("payToken") String payToken){
		//验证参数
		if(StringUtils.isEmpty(payToken)) {
			return BaseApiService.setResultError("payToken不能为空");
		}
		//判断token有效期
		String payId = (String) redisService.getString(payToken);
		if(StringUtils.isEmpty(payId)) {
			return BaseApiService.setResultError("支付超时！");
		}
		//使用token查询redis，获取到支付id
		Long payIDI = Long.parseLong(payId);
		//支付id获取支付信息
		PaymentInfo paymentInfo = payDao.getPaymentInfo(payIDI);
		if(paymentInfo==null) {
			return BaseApiService.setResultError("未找到支付类型");
		}
		//使用支付id，进行下单
		
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.gatewayUrl, alipayConfig.app_id, alipayConfig.merchant_private_key, "json", alipayConfig.charset, alipayConfig.alipay_public_key, alipayConfig.sign_type);
		
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(alipayConfig.return_url);
		alipayRequest.setNotifyUrl(alipayConfig.notify_url);
		
		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = paymentInfo.getOrderId();
		//付款金额，必填
		String total_amount = paymentInfo.getPrice()+"";
		//订单名称，必填
		String subject = "会员支付";
		//商品描述，可空
//		String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
		
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
//				+ "\"body\":\""+ body +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		
		//若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
		//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
		//		+ "\"total_amount\":\""+ total_amount +"\"," 
		//		+ "\"subject\":\""+ subject +"\"," 
		//		+ "\"body\":\""+ body +"\"," 
		//		+ "\"timeout_express\":\"10m\"," 
		//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
		String result = null;
		try {
			//对接支付宝接口
			 result = alipayClient.pageExecute(alipayRequest).getBody();

		} catch (AlipayApiException e) {
			BaseApiService.setResultError("支付异常");
		}
		//返回一个订单form表单信息
		JSONObject data = new JSONObject();
		data.put("payHtml", result);
		return BaseApiService.setResultSuccess(data);
	}

}
